package com.example.demo.service;

import com.example.demo.dao.LoginTicketDao;
import com.example.demo.dao.UserDao;
import com.example.demo.model.LoginTicket;
import com.example.demo.model.Result;
import com.example.demo.model.User;
import com.example.demo.util.ToutiaoUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by admin on 2017/10/9.
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private LoginTicketDao loginTicketDao;

    public List<User> getAllUser(){return userDao.selectAll();}

    public User getUserById(int userId){
        return userDao.selectById(userId);
    }

    /**
     *
     * @param username
     * @param password
     * @return
     */
    public Map<String,Object> regis(String username, String password){

       Map<String,Object> map=new HashMap<>();
        if(StringUtils.isBlank(username)){
            map.put("msg","用户名不能为空");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("msg","密码不能为空");
            return map;
        }
        User user=userDao.selectByName(username);
        if(user!=null){
            map.put("msg","用户名已经被注册");
            return map;
        }
        User user1=new User();
        user1.setName(username);
        user1.setSalt(UUID.randomUUID().toString().substring(0,5));
        user1.setHeadUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user1.setPassword(ToutiaoUtil.MD5(password+user1.getSalt()));

        userDao.addUser(user1);

        String ticket=addTicket(user1.getId());
        map.put("ticket",ticket);
        return map;
    }

    //注册成功在数据库里面添加ticket
    public String addTicket(int userId){
        LoginTicket ticket=new LoginTicket();
        ticket.setUserId(userId);
       Date date=new Date();
       date.setTime(date.getTime()+1000*3600*24*5);
       ticket.setExpired(date);
       ticket.setStatus(0);
       ticket.setTicket(UUID.randomUUID().toString().replaceAll("-",""));
       loginTicketDao.addTicket(ticket);
        return ticket.getTicket();
    }

}
